package com.dj.ms.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.dj.ms.annotation.Interceptor;
import com.dj.ms.annotation.Unauthorize;
import com.dj.ms.session.SessionCollector;
import com.dj.ms.support.SpringBeanFactoryUtils;
import io.prometheus.client.Counter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.UrlPathHelper;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <br>
 * <p>
 * - prometheus interceptor
 * </p>
 *
 * <br>
 *
 * @author ZJG
 * @version 1.0
 * @date 2021/11/10 上午9:35
 */
@Slf4j
@Interceptor(order = Ordered.LOWEST_PRECEDENCE)
@Component
public class PrometheusInterceptor extends HandlerInterceptorAdapter {

    private UrlPathHelper urlPathHelper = new UrlPathHelper();

    @Autowired
    private Counter requestTotalCountCollector;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = urlPathHelper.getLookupPathForRequest(request);
        String method = "", code = String.valueOf(response.getStatus());
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            method = handlerMethod.getMethod().getName();
        }
        if (ObjectUtil.isNull(this.requestTotalCountCollector)) {
            this.requestTotalCountCollector = SpringBeanFactoryUtils.getBean("requestTotalCountCollector");
        }
        if (ObjectUtil.isNotNull(this.requestTotalCountCollector)) {
            requestTotalCountCollector.labels(requestURI, method, code).inc();
        }
        return super.preHandle(request, response, handler);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
